package net.xdclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.fegin.CouponFeignService;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.model.UserDO;
import net.xdclass.mapper.UserMapper;
import net.xdclass.request.NewUserCouponRequest;
import net.xdclass.request.UserLoginRequest;
import net.xdclass.request.UserRegisterRequest;
import net.xdclass.service.NotifyService;
import net.xdclass.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xdclass.until.CommonUtil;
import net.xdclass.until.JWTUtil;
import net.xdclass.until.JsonData;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import net.xdclass.vo.UserVO;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 二当家小D
 * @since 2022-01-07
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    @Autowired
    private NotifyService notifyService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CouponFeignService couponFeignService;

    @Override
//    @GlobalTransactional
    public JsonData register(UserRegisterRequest userRegisterRequest) {
        boolean checkCode = false;
        if (StringUtils.isNotBlank(userRegisterRequest.getMail())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, userRegisterRequest.getMail(), userRegisterRequest.getCode());
        }
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userRegisterRequest, userDO);
        userDO.setCreateTime(new Date());
        userDO.setSlogan(userRegisterRequest.getSlogan());
        //生成秘钥
        userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        //密码 + 加盐处理
        String cryptPwd = Md5Crypt.md5Crypt(userRegisterRequest.getPwd().getBytes(), userDO.getSecret());
        userDO.setPwd(cryptPwd);

        if (checkUnique(userDO.getMail())) {
            boolean save = userService.save(userDO);
            //TODO 新用户注册福利
            userRegisterInitTask(userDO);
            log.info(userDO.toString() + ">>注册成功");
            return JsonData.buildSuccess();
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
        }
    }

    /**
     * 登录
     *
     * @param loginRequest
     * @return
     */
    @Override
    public JsonData login(UserLoginRequest loginRequest) {

        List<UserDO> list = list(
                new QueryWrapper<UserDO>().eq("mail", loginRequest.getMail()));

        if (list != null && list.size() == 1) {
            UserDO userDO = list.get(0);
            String cryptPwd = Md5Crypt.md5Crypt(loginRequest.getPwd().getBytes(), userDO.getSecret());
            if (cryptPwd.equals(userDO.getPwd())) {
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(userDO, loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);
                //TODO 刷新token
//              String refreshToken = CommonUtil.generateUUID();
//              redisTemplate.opsForValue().set(refreshToken,"",1000*60*60*24*30);

                return JsonData.buildSuccess(token);
            }
            //密码错误
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
        } else {
            //未注册
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }

    }

    @Override
    public UserVO findUserDetail() {
        LoginUser loginUser = LoginInterceptor.loginUserThreadLocal.get();
        UserDO userDO = userService.getOne(new QueryWrapper<UserDO>().eq("id", loginUser.getId()));
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userDO, userVO);
        return userVO;
    }

    private boolean checkUnique(String mail) {
        LambdaQueryWrapper<UserDO> eq = new LambdaQueryWrapper<UserDO>().eq(UserDO::getMail, mail);
        List<UserDO> list = list(eq);
        return list.size() > 0 ? false : true;
    }

    //用户注册,初始化福利信息
    private void userRegisterInitTask(UserDO userDO) {
        NewUserCouponRequest newUserCouponRequest = new NewUserCouponRequest();
        newUserCouponRequest.setName(userDO.getName());
        newUserCouponRequest.setUserId(userDO.getId());
        JsonData jsonData = couponFeignService.addNewUserCoupon(newUserCouponRequest);
        log.info("发放新用户注册优惠券:{},结果:{}", newUserCouponRequest.toString(), jsonData.toString());
    }
}
